# import requests
import json
import os
from openai import OpenAI

class DashscopeApi:
    def __init__(self, api_key=None):
        # 问题可能出在下面这行，确保正确缩进
        self.api_key = api_key or os.environ.get("DASHSCOPE_API_KEY")
        if not self.api_key:
            raise ValueError("请设置通义千问API_KEY")
        self.url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
        # self.headers = {
        #     "Content-Type": "application/json",
        #     "Authorization": f"Bearer {self.api_key}"
        # }

    def get_answer(self,prompt):
        try:
            client = OpenAI(
            # 若没有配置环境变量，请用阿里云百炼API Key将下行替换为：api_key="sk-xxx",
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            # os.getenv("DASHSCOPE_API_KEY"),
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
            )
            # response = requests.post(self.url, headers=self.headers, data=json.dumps(payload))
            completion = client.chat.completions.create(
            model="qwen-plus",  # 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
            messages=[
                {'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': prompt}
                ]
            )
            return completion.choices[0].message.content
  
        except Exception as e:
            print(f"错误信息：{e}")
            print("请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

        # return response.json()["output"]["text"]



# import os
# from openai import OpenAI

# try:
    # client = OpenAI(
    #     # 若没有配置环境变量，请用阿里云百炼API Key将下行替换为：api_key="sk-xxx",
    #     api_key=os.getenv("DASHSCOPE_API_KEY"),
    #     # os.getenv("DASHSCOPE_API_KEY"),
    #     base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    # )

#     completion = client.chat.completions.create(
#         model="qwen-plus",  # 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
#         messages=[
#             {'role': 'system', 'content': 'You are a helpful assistant.'},
#             {'role': 'user', 'content': '你是谁？'}
#             ]
#     )
#     # print(os.getenv("DASHSCOPE_API_KEY"),"dsdds");
#     print(completion.choices[0].message.content)
# except Exception as e:
#     print(f"错误信息：{e}")
#     print("请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code")